<template>
  <div>
    <div class="alarmDetailWord"></div>
    <div class="edit-space"></div>
    <el-row type="flex" v-show="!disabled" class="create-input" justify="center" align="middle">
        <el-col :span="2">策略名称</el-col>
        <el-col :span="18">
           </span><el-input v-model="strategyName" :disabled="disabled" :maxlength="50" placeholder="请输入名称" size="small"></el-input> 
        </el-col>
    </el-row>
    <el-row type="flex" v-show="!disabled" class="create-input create-description" justify="center" align="middle">
        <el-col :span="2">策略描述</el-col>
        <el-col :span="18">
           </span><el-input v-model="strategyDescription" :disabled="disabled" :maxlength="100" type="textarea" placeholder="请输入描述" size="small"></el-input> 
        </el-col>
    </el-row>
    <!-- <el-row type="flex" class="create-input create-description" justify="center" align="middle">
        <el-col :span="2">告警等级</el-col>
        <el-col :span="18">
          <el-select v-model="strategyLevel" :disabled="disabled" placeholder="请选择告警等级" size="small">
            <el-option
              v-for="item in ruleMoreData"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-col>
    </el-row> -->
     <el-row type="flex" justify="center" align="middle" style="margin-bottom: 15px;">
        <el-col :span="8" :offset="12" style="text-align: right;" v-show="!disabled">
          <!-- <el-button @click="alarmSettings" type="primary" size="small">告警发送设置</el-button> -->
          <el-button @click="addRule" type="primary" size="small">新增规则</el-button>
        </el-col>
    </el-row>
    <el-row type="flex" class="create-rule-container" justify="center" align="middle" v-if="v.operate !== 'delete'" v-for="(v, i) in ruleCard" :key="i">
        <el-col :span="ruleSpan" class="create-rule-card">
          <el-row align="middle" type="flex" class="rule">
            <el-col :span="2">规则名称</el-col>
            <el-col :span="18">
              <el-input v-model="v.ruleName" :maxlength="50" placeholder="请输入规则名称" size="small"></el-input>
            </el-col>
          </el-row>
          <el-row align="middle" type="flex" class="rule rule-pad">
            <el-col class="rule-more-table">
              <el-table :data="v.ruleIndexData">
                <el-table-column prop="name" label="监控指标">
                  <template scope="scope">
                    <el-select @change="ruleChange(scope.row.index, i, scope.$index, scope.row)" v-model="scope.row.index" placeholder="请选择规则指标" size="small">
                      <el-option
                        v-for="item in scope.row.indexData"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                      </el-option>
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column prop="level" label="规则条件" width="160">
                  <template scope="scope">
                    <el-select v-model="scope.row.condition" @change="ruleConditionChange(i)" placeholder="请选择规则条件" size="small">
                      <el-option
                        v-for="item in scope.row.conditionData"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                      </el-option>
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column prop="threshold" label="阈值">
                  <template scope="scope">
                    <div style="display: flex;align-items:center;">
                      <el-input style="width: 80px;" type="text" @paste="() => {return false}" @change="thresholdChange(scope.row.threshold, scope.row, v.unit[scope.$index])" v-model="scope.row.threshold" min="0" placeholder="阈值" class="rule-threshold-input" size="small"></el-input>
                      <span style="margin-left: 10px;">{{ v.unit.length ? v.unit[scope.$index] : ''}}</span>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column prop="average" label="统计粒度" width="100">
                  <template scope="scope">{{scope.row.index ? v.granularity[scope.$index] + ' min' : ''}}</template>
                </el-table-column>
                <el-table-column label="关系">
                  <template scope="scope">
                    <span v-show="scope.row.operator === '&&'">并且</span>
                    <span v-show="scope.row.operator === '||'">或者</span>
                  </template>
                </el-table-column>
                <el-table-column prop="active" label="操作" width="100">
                  <template scope="scope">
                    <el-popover
                      placement="top"
                      width="20"
                      trigger="click"
                      v-model="scope.row.logic"
                      >
                      <div style="text-align: center; margin: 0">
                        <el-button size="mini" type="text" @click.native="newRule(i, scope.row, '&&', scope.$index)">并且</el-button>
                        <el-button type="text" size="mini"  @click.native="newRule(i, scope.row, '||', scope.$index)">或者</el-button>
                      </div>
                      <el-button type="text" size="small" v-show="scope.row.add && v.ruleIndexData.length < 10" slot="reference">添加</el-button>
                    </el-popover>
                    <span class="rule-del-btn" v-show="v.ruleIndexData.length > 1" @click="delRule(i, v.ruleIndexData[scope.$index - 1], scope.row, scope.$index)">删除</span>
                  </template>
                </el-table-column>
              </el-table>
            </el-col>
          </el-row>
          <!-- <el-row class="rule rule-pad" v-show="v.showRule">
            <el-col :span="24">
              <el-row align="middle" type="flex" class="rule-time" style="text-align: left">
                <el-col>
                  <el-radio-group v-model="v.ruleRadio"  @change="ruleRadioChange(v, i, v.ruleRadio)"  size="small">
                    <el-radio v-for="(item, index) in v.ruleRadioData" :label="index" :key="index">{{v.strategyNameArr[index]}}</el-radio>
                  </el-radio-group>
                </el-col>
              </el-row>
              <el-row class="rule-more-table">
                <el-col>
                  <el-table :data="ruleMoreData[i]">
                    <el-table-column prop="alarmName" label="告警名称">asdasd</el-table-column>
                    <el-table-column prop="alarmCode" label="告警级别">1</el-table-column>
                    <el-table-column prop="thresholdStop" label="阈值">
                      <template scope="scope">
                        <el-input type="number" min="0" @blur="ruleMoreThresholdChange(v.ruleIndexData[v.ruleRadio].thresholdLevel[scope.$index], i, scope.$index)" @paste="() => {return false}" v-model="v.ruleIndexData[v.ruleRadio].thresholdLevel[scope.$index]" size="small" placeholder="请输入">2222</el-input>
                      </template>
                    </el-table-column>
                  </el-table>
                </el-col>
              </el-row>
            </el-col>
          </el-row> -->
          <!-- <div class="rule-bottom-more hovering" @click="showRuleMore(i, v)">
            <i :class="[v.showRule ? 'el-icon-caret-top' : 'el-icon-caret-bottom']"></i>
          </div> -->
          <i class="icon ion-android-close rule-close" v-if="ruleCard.length > 1 && !disabled" @click.stop="removeRule(i)"></i>
        </el-col>
    </el-row>
    <el-row type="flex" class="create-btn-container" justify="center" align="middle" v-if="!disabled">
        <el-col :span="11" class="create-btn">
          <el-button type="primary" size="small" @click="ruleSave">修改</el-button><span class="interval"></span><router-link to="/strategy"><el-button size="small">取消</el-button></router-link>
        </el-col>
    </el-row>
    <el-dialog
      title="提示"
      :visible.sync="delStrategyRuleVisible"
      size="tiny">
      <span>确定要删除该条规则吗？</span>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="delStrategyRuleVisible = false">取 消</el-button>
        <el-button size="small" type="primary" @click="delStrategyRuleSubmit">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="告警发送设置"
      :visible.sync="alarmSetVisible"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :show-close="false"
      size="large">
      <el-row>
        <el-col class="alarm-set-col" :span="21" :offset="3">
          <span class="set-alarm-label">发送通道</span>
          <el-select v-model="channel" size="small" placeholder="请选择">
            <el-option
              v-for="item in channelData"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-col>
      
        <el-col class="alarm-set-col" :span="21" :offset="3">
        <span class="set-alarm-label">告警等级</span>
          <el-select v-model="strategyLevel" :disabled="disabled" placeholder="请选择告警等级" size="small">
            <el-option
              v-for="item in ruleMoreData"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-col>
        <el-col class="alarm-set-col" :span="21" :offset="3">
          <span class="set-alarm-label">发送频率</span>
          <div class="set-alarm-content">
            <span>每</span>
            <el-input @change="checkTimeNumber" style="width: 25%;" v-model="timeSet" class="time-input" size="small"></el-input>
            <span>分钟，发送</span>
            <el-input @change="checkCountNumber" style="width: 10%;" v-model="count" :disabled="true" class="time-input" size="small"></el-input>
            <span>次</span>
          </div>
        </el-col>
        <el-col class="alarm-set-col" :span="21" :offset="3">
          <span class="set-alarm-label">告警主题</span>
          <div class="set-alarm-content">
            <el-input size="small" placeholder="请输入告警主题" v-model="theme"></el-input>
          </div>
        </el-col>
        <el-col class="alarm-set-col" :span="21" :offset="3">
          <span class="set-alarm-label set-alarm-textarea">告警内容</span>
          <div class="set-alarm-content">
            <el-input type="textarea" placeholder="请输入告警内容" :rows="4" size="small" v-model="content"></el-input>
          </div>
        </el-col>
      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="alarmSetCancel">取 消</el-button>
        <el-button size="small" type="primary" @click="alarmSetVisible = false">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
  import { Table, TableColumn, Row, Col, Button, Input, Select, Option, Popover, Radio, RadioGroup, Message, Dialog } from 'element-ui'
  export default {
    props: ['changeId', 'req', 'editRule', 'selectChange'],
    data () {
      return {
        data: [{
          strategy: 'name'
        }],
        strategyName: '',
        strategyDescription: '',
        ruleMoreData: [],
        time: '',
        showRule: false,
        ruleCard: [],
        ruleArr: [],
        ruleTypeRadio: '0',
        alarmItem: [],
        alarmLevelsObj: [],
        strategyGetData: '',
        granularity: [],
        alarmQuotaName: '',
        levelsArray: [],
        delStrategyRuleVisible: false,
        ruleCodeIndex: '',
        strategyLevel: '',
        flag: true,
        disabled: false,
        delRuleData: [],
        delStopEvent: false,
        alarmSetVisible: false,
        channelData: [
          {
            value: 'Onduty'
          }
        ],
        channel: 'Onduty',
        timeSet: 5,
        theme: '',
        content: '',
        count: 1,
        initStrategyName: '',
        initFlag: false,
        ruleSpan: 20,
        step: false
      }
    },
    created () {
      this._strategyEditByRoute()
      this._alarmLevels()
      this._alarmItem()
      // this._alarmSendConfig()
      // this._initStrategy()
    },
    watch: {
      '$route': {
        deep: true,
        handler () {
          console.log(2222)
          this.step = true
        }
      },
      ruleTypeRadio (v) {
        this.alarmItem = []
        this._resetRule()
      },
      ruleCard: {
        deep: true,
        handler (v) {
          if (this.flag) {
            this.ruleCard = v
            this.flag = false
            return
          }
          this.$emit('changeValue', true)
        }
      },
      changeId (v) {
        this._initStrategy()
      },
      strategyName (v) {
        if (v != this.initStrategyName) {
          this.initFlag = true
        } else {
          this.initFlag = false
        }
      },
      editRule (v) {
        console.log(1111, v)
        this.ruleSave()
      }
    },
    methods: {
      alarmSetCancel () {
        this.alarmSetVisible = false
        this.theme = ''
        this.content = ''
      },
      checkTimeNumber (v) {
        this.$nextTick(() => {
          this.timeSet = v.replace(/[^\d]/g, '')
        })
      },
      checkCountNumber (v) {
        this.$nextTick(() => {
          this.count = v.replace(/[^\d]/g, '')
        })
      },
      alarmSettings () {
        this.alarmSetVisible = true
      },
      closeStrategyMore () {
        this.$emit('closeStrategyMore')
      },
      _strategyEditByRoute () {
        if (this.$route.name === 'strategy-list-more') {
          this.disabled = true
          this.ruleSpan = 24
        } else {
          this.ruleSpan = 20
          this.disabled = false
        }
        // if ( this.$route.name === 'check-instance-strategy-more' || this.$route.name === 'monitor-strategy-more') {
        //   this.disabled = true
        // } else {
        //   this.disabled = false
        // }
      },
      showRuleMore (i, v) {
        var arr = []
        v.ruleRadioData = []
        v.ruleIndexData.map(function (k, j) {
          if (!k.condition || !k.index || !k.threshold) {
            v.more = false
          } else {
            v.more = true
          }
        })
        if (!v.more) {
          return Message('指标、条件、级别阈值不能为空')
        }
        v.ruleIndexData.some((k, j) => {
          v.ruleRadioData.push(j)
          this.alarmItem.some((s, n) => {
            if (k.index === s.value) {
              this.ruleCard[i].strategyNameArr[j] = s.label
            }
          })
        })
        // this.ruleMoreData[i].some((k, j) => {
        //   if (k.thresholdStop) {
        //     this.ruleCard[i].thresholdLevel.push(k.thresholdStop)
        //   }
        // })
        this.ruleCard[i].showRule = !this.ruleCard[i].showRule
      },
      addRule () {
        if (this.ruleCard.length > 9) {
          return Message('只允许创建十条规则')
        }
        this.ruleCard.push({
          showRule: false,
          ruleName: '',
          operate: 'save',
          ruleIndexData: [
            {
              conditionData: [
                {
                  value: '<=',
                  label: '小于等于'
                },
                {
                  value: '>=',
                  label: '大于等于'
                }
              ],
              indexData: this.alarmItem,
              condition: '',
              index: '',
              add: true,
              logic: false,
              operator: '',
              threshold: '',
              thresholdLevel: []
            }
          ],
          more: false,
          ruleRadioData: [],
          ruleRadio: 0,
          unit: [],
          strategyNameArr: [],
          granularity: this.granularity,
          isNew: true
        })
        this.ruleMoreData.push(this.levelsArray[0])
      },
      removeRule (i) {
        // delRuleData
        if (this.ruleCard[i].operate === 'update') {
          this.ruleCard[i].operate = 'delete'
          // var data = this.ruleCard[i]
          this.delRuleData.push(this.ruleCard[i])
        }
        this.delStopEvent = true
        this.ruleCard.splice(i, 1)
        // console.log(this.ruleCard[i])
        // this.ruleCodeIndex = i
        // if (this.ruleCard[i].isNew) {
        //   this.ruleCard.splice(i, 1)
        // } else {
        //   // this.delStrategyRuleVisible = true
        // }
      },
      async delStrategyRuleSubmit () {
        var data = {
          ruleCode: this.ruleCard[this.ruleCodeIndex].ruleCode
        }
        await this.api.delStrategyRuleByCode({data: data})
        this.ruleCard.splice(this.ruleCodeIndex, 1)
        this.delStrategyRuleVisible = false
      },
      delRule (s, p, n, i) {
        this.ruleArr[s].ruleIndexData.splice(i, 1)
        this.ruleArr[s].ruleRadioData.splice(i, 1)
        this.ruleArr[s].unit.splice(i, 1)
        this.ruleArr[s].ruleIndexData.some((k, j) => {
          if (this.ruleArr[s].alarmQuotaName == k.index) {
            this.ruleArr[s].ruleRadio = j
          } else {
            this.ruleArr[s].ruleRadio = 0
          }
        })
        var ss = this.ruleArr[s].ruleIndexData
        if (ss[ss.length - 1].operator) {
          this.ruleArr[s].ruleIndexData[ss.length - 1].operator = ''
        }
        if (p && n.add) {
          p.add = true
        }
        this.delStopEvent = true
      },
      newRule (i, obj, str, s) {
        if (!obj.index || !obj.condition || !obj.threshold) {
          obj.logic = false
          return Message('指标、条件、级别阈值不能为空')
        }
        obj.operator = str
        this.ruleCard[i].showRule = false
        this.ruleCard[i].ruleRadioData.push(s + 1)
        this.ruleArr = this.ruleCard
        this.ruleArr[i] = Object.assign({
          ruleIndexData: [],
        }, this.ruleCard[i])
        this.ruleArr[i].ruleIndexData.push(
          {
            conditionData: [
              {
                value: '<=',
                label: '小于等于'
              },
              {
                value: '>=',
                label: '大于等于'
              }
            ],
            indexData: this.alarmItem,
            condition: '',
            index: '',
            add: true,
            threshold: '',
            logic: false,
            operator: ''
          }
        )
        obj.logic = false
        obj.add = false
        this.ruleCard = [].concat(this.ruleArr)
      },
      popoverHide (obj) {
        obj.logic = false
      },
      ruleChange (v, n, s, obj) {
        if (!this.step) {
          if (!this.delStopEvent) {
            this.alarmItem.some((k, i) => {
              if (k.value == v) {
                this.ruleCard[n].granularity.splice(s, 1, k.itemGranularity)
                this.ruleCard[n].unit.splice(s, 1, k.unit)
                this.ruleCard[n].strategyNameArr.splice(s, 1, k.label)
                if (this.$route.name === 'edit-strategy') {
                  obj.threshold = ''
                }
              }
            })
          } else {
            this.delStopEvent = false
          }
        }
      },
      ruleConditionChange (i) {
        // this.ruleCard[i].ruleIndexData[this.ruleCard[i].ruleRadio].thresholdLevel.splice(0, this.ruleCard[i].ruleIndexData[this.ruleCard[i].ruleRadio].thresholdLevel.length)
      },
      thresholdChange (v, obj, unit) {
        this.$nextTick(() => {
          var val = v
          if (v.indexOf('.') !== -1) {
            if (val.match(/\./g).length > 1) {
              obj.threshold = this.thresholdVal.substring(0, this.thresholdVal.indexOf('.') + 2)
            }
            if (val.match(/\./g).length === 1) {
              if (v.length === 1) {
                this.thresholdVal = '0.'
              } else {
                this.thresholdVal = v.replace( /[^\d\.]/g, '0')
              }
              obj.threshold = this.thresholdVal.substring(0, this.thresholdVal.indexOf('.') + 2)
            }
          } else {
            obj.threshold = v.replace( /[^\d\.]/g, '')
            if (v.length > 1 && v.substring(0, 1) == 0) {
              obj.threshold = v.substring(1)
            } else {
              val = v
            }
          }
          if (unit === '%') {
            if (v > 100) {
              obj.threshold = 100
            }
          }
        })
      },
      ruleRadioChange (v, i, s) {
        // this.ruleCard[i].thresholdLevel.splice(0, this.ruleCard[i].thresholdLevel.length)
        this.ruleCard[i].alarmQuotaName = this.ruleCard[i].ruleIndexData[s].index
      },
      ruleMoreThresholdChange (v, i, s) {
        var rule = this.ruleCard[i].ruleIndexData[this.ruleCard[i].ruleRadio]
        var val = +(rule.thresholdLevel[s])
        this.$nextTick(() => {
          if (v == 0) {
            rule.thresholdLevel.splice(s, 1,  '')
          }
          // console.log(rule)
          if (rule.condition === '<' || rule.condition === '小于等于') {
            if (s === 0) {
              if (val >= rule.threshold) {
                Message('该阈值必须要小于指标阈值')
                rule.thresholdLevel.splice(s, 1, '')
              }
            } else {
              if (s == (this.ruleMoreData[i].length - 1)) {
                rule.thresholdLevel.splice(s, 1, rule.threshold)
              } else {
                if (!rule.thresholdLevel[s - 1]) {
                  Message('请填写上一个阈值')
                  rule.thresholdLevel.splice(s, 1, '')
                } else {
                  if (val <= rule.thresholdLevel[s - 1] || val == rule.thresholdLevel[s - 1] || val >= rule.threshold) {
                    Message('该值必须大于上一个阈值并且小于指标阈值')
                    rule.thresholdLevel.splice(s, 1, '')
                  }
                  if (val >= rule.thresholdLevel[s + 1]) {
                    rule.thresholdLevel.splice((s + 1), 1, '')
                  }
                }
              }
            }
          } else {
            if (s === 0) {
              if (val <= rule.threshold) {
                Message('该值必须要大于指标阈值')
                rule.thresholdLevel.splice(s, 1, '')
              }
            } else {
              if (!rule.thresholdLevel[s - 1]) {
                Message('请填写上一个阈值')
                rule.thresholdLevel.splice(s, 1, '')
              } else {
                if (s === (this.ruleMoreData[i].length - 1)) {
                  rule.thresholdLevel.splice(s, 1, rule.threshold)
                } else {
                  if (val >= rule.thresholdLevel[s - 1] || val <= rule.threshold) {
                    Message('该值必须要小于上一个值并且大于指标阈值')
                    rule.thresholdLevel.splice(s, 1, '')
                  }
                  if (val <= rule.thresholdLevel[s + 1]) {
                    rule.thresholdLevel.splice((s + 1), 1, '')
                  }
                }
              }
              // console.log(this.ruleMoreData.length, 'sdasdsadsadsad')
            }
          }
        })
      },
      async ruleSave () {
        if (!this.editRule) {
          var check = ''
          if (this.initFlag) {
            check = await this.api.strategyCheckNameExist({data: {strategyName: this.strategyName}})
          }
          if (check.total) {
            Message('该策略名称已存在， 请重新输入策略名称')
            this.strategyNmae = ''
            return
          }
        }
        var isChecked = this._checkSaveOptions()
        if (isChecked) {
          return
        }
        this.delRuleData.some((v, i) => {
          this.ruleCard.push(v)
        })
        var id = this.$route.query.id || this.$route.params.id
        var data = {
          strategyName: this.strategyName,
          strategyDesc: this.strategyDescription,
          updateUser: '',
          ruleVO: []
        }
        this.ruleMoreData.some((k, j) => {
          if (this.strategyLevel === k.label) {
            this.strategyLevel = k.value
          }
        })
        data.level = this.strategyLevel
        this.ruleCard.some((v, i) => {
          var surplus = []
          var ruleAlarm = []
          var triggerQuotaName = ''
          var triggerRule = ''
          var triggerThreshold = ''
          var triggerUnit = ''
          v.ruleIndexData.some((k, j) => {
            triggerQuotaName += ',' + k.index
            if (k.condition === '小于等于') {
              k.condition = '<='
            } else if (k.condition === '大于等于') {
              k.condition = '>='
            }
            triggerRule += ' ' + k.index + k.condition + k.threshold + ' ' + k.operator
            triggerThreshold += ',' + k.threshold,
            triggerUnit += ',' + v.unit[j]
            if (k.condition == '>=') {
              k.condition = '大于等于'
            } else if (k.condition == '<=') {
              k.condition = '小于等于'
            } else {
              k.condition = k.condition
            }
            surplus.push({
              index: k.index,
              condition: k.condition,
              threshold: k.threshold,
              operator: k.operator,
              unit: v.unit[j]
            })
          })
          // this.ruleMoreData[i].some((k, n) => {
          //   ruleAlarm.push({
          //     alarmName: k.alarmName,
          //     alarmCode: k.alarmCode,
          //     thresholdStart: n === 0 ? 0 : v.ruleIndexData[v.ruleRadio].thresholdLevel[n - 1],
          //     thresholdStop: +(v.ruleIndexData[v.ruleRadio].thresholdLevel[n])
          //   })
          // })
          data.ruleVO.push({
            alarmQuotaName: v.alarmQuotaName || v.ruleIndexData[0].index,
            ruleName: v.ruleName,
            ruleCode: v.ruleCode,
            triggerQuotaName: triggerQuotaName.substring(1),
            triggerRule: triggerRule,
            triggerThreshold: triggerThreshold.substring(1),
            triggerUnit: triggerUnit.substring(1) || 'min',
            updateUser: '',
            operate: v.operate,
            ruleSurplus: JSON.stringify(surplus)
          })
        })
        Object.assign(this.strategyGetData, data)
        data.strategyCode = this.strategyGetData.strategyCode
        await this.api.strategyUpdate({data: data})
        // this.$router.push('/strategy/list')
      },
      _checkSaveOptions () {
        var data = false
        // if (!this.strategyLevel) {
        //   data = true
        //   Message('告警等级不能为空')
        // }
        if (!this.strategyName) {
          data = true
          Message('策略名称，策略描述不能为空')
        } else {
          this.ruleCard.some((v ,i) => {
            if (!v.ruleName) {
              data = true
              Message('规则名称不能为空')
            } else {
              v.ruleIndexData.some((k, j) => {
                if (!k.index || !k.condition || !k.threshold) {
                  data = true
                  Message('规则名称：' + v.ruleName + '指标、条件、级别阈值不能为空')
                }
              })
            }
            // this.ruleMoreData.some((k , n) => {
            //   k.some((u, j) => {
            //     if (!v.ruleIndexData[v.ruleRadio].thresholdLevel[j]) {
            //       console.log('zhibianyuzhiyoukongzhi la')
            //       data = true
            //       Message('规则名称：' + v.ruleName + '更多选项告警阈值有空值')
            //     }
            //     console.log(v.ruleIndexData[v.ruleRadio].condition)
            //     if (v.ruleIndexData[v.ruleRadio].condition === '小于') {
            //       console.log(3333)
            //       // if (v.ruleIndexData[v.ruleRadio].threshold != v.thresholdLevel[0]) {
            //       //   data = true
            //       //   Message('规则名称：' + v.ruleName + '（指标阈值与更多选项的第一个阈值不想等）')
            //       // }
            //     }
            //     if (v.ruleIndexData[v.ruleRadio].condition === '大于') {
            //       // if (v.ruleIndexData[v.ruleRadio].threshold != v.thresholdLevel[v.thresholdLevel.length - 1]) {
            //       //   console.log(v.ruleIndexData[v.ruleRadio].threshold, v.thresholdLevel[v.thresholdLevel.length - 1])
            //       //   data = true
            //       //   Message('规则名称：' + v.ruleName + '（指标阈值与更多选项的最后一个阈值不想等）')
            //       // }
            //     }
            //   })
            // })
          })
        }
        return data
      },
      _resetRule () {
        this.ruleCard.some((v, i) => {
          v.ruleIndexData.some((k, j) => {
            k.index = ''
            k.condition = ''
            k.threshold = ''
          })
          v.showRule = false
          v.more = false
        })
      },
      async _alarmLevels () {
        var data  = await this.api.alarmLevels()
        data.data.some((v, i) => {
          this.ruleMoreData.push({
            value: v.alarmLevelCode,
            label: v.alarmLevelNameZh
          })
        })
        this._initStrategy()
      },
      async _initStrategy () {
        // if (this.$route.query.id === 'undefined' || !this.$route.query.id) {
        //   Message('系统繁忙请稍后再试')
        //   return
        // }
        var id = this.$route.query.id || this.$route.params.id
        var data = await this.api.strategyGetOne({data: {strategyCode: id}})
        this.ruleArr = this.ruleCard = []
        this.strategyName = data.data[0].strategyName
        this.initStrategyName = data.data[0].strategyName
        this.strategyDescription = data.data[0].strategyDesc
        // this.strategyLevel = data.data[0].level
        this.$nextTick(() => {
          this.ruleMoreData.some((k, j) => {
            if (data.data[0].level == k.value) {
              this.strategyLevel = k.label
            }
          })
        })
        var sdata = data.data[0].ruleVO
        var arrs = []
        var levelsArray = []
        sdata.some((v, i) => {
          arrs[i] = []
          levelsArray = [[]]
          var flag = 0
          // v.ruleAlarm.some((k, j) => {
            
          //   if (j === 0) {
          //     if (k.thresholdStop) {
          //         flag = 0
          //     } else {
          //         flag = 1
          //     }
          //   }
          //   if (flag == 0) {
          //     arrs[i].push({
          //       alarmCode: k.alarmCode,
          //       alarmName: k.alarmName,
          //       thresholdStart: k.thresholdStop
          //     })
          //   } else {
          //     arrs[i].push({
          //       alarmCode: k.alarmCode,
          //       alarmName: k.alarmName,
          //       thresholdStart: k.thresholdStart
          //     })
          //   }
          //   levelsArray[0].push({
          //     alarmCode: k.alarmCode,
          //     alarmName: k.alarmName
          //   })
          // })
        })
        this.levelsArray = levelsArray
        var arr = []
        data.data[0].ruleVO.some((v, i) => {
          var data = []
          arr.push({
            showRule: false,
            ruleName: v.ruleName,
            ruleIndexData: [],
            more: false,
            ruleRadioData: [],
            ruleRadio: 0,
            unit: [],
            strategyNameArr: [],
            operate: 'update',
            granularity: this.granularity,
            ruleCode: v.ruleCode,
            alarmQuotaName: v.alarmQuotaName,
          })
          
          if (v.ruleSurplus) {

            JSON.parse(v.ruleSurplus).some((k, j) => {
              var thresholdLevel = []
              arr[i].ruleRadioData.push(j)
              data.push({})
              data[j].index = k.index
              data[j].condition = k.condition
              data[j].threshold = k.threshold
              data[j].operator = k.operator
              data[j].indexData = this.alarmItem
              data[j].conditionData = [
                {
                  value: '<=',
                  label: '小于等于'
                },
                {
                  value: '>=',
                  label: '大于等于'
                }
              ]
              if (j == JSON.parse(v.ruleSurplus).length - 1) {
                data[j].add = true
              } else {
                data[j].add = false
              }
              data[j].logic = false
              arr[i].unit.push(k.unit)
              if (arr[i].alarmQuotaName === k.index) {
                arr[i].ruleRadio = j
              }
            })
          }
          arr[i].ruleIndexData = data
        })
        this.ruleArr = this.ruleCard = arr
        this.strategyGetData = data.data[0]
      },
      async _alarmItem () {
        var data = await this.api.alarmItem()
        data.data.some((v, i) => {
          this.alarmItem.push({
            value: v.itemCode,
            label: v.itemName,
            unit: v.itemUnit,
            itemGranularity: v.itemGranularity
          })
          this.granularity.push(v.itemGranularity)
        })
        // this.ruleCard[0].ruleIndexData[0].indexData = this.alarmItem
      },
      async _alarmSendConfig () {
        var id = this.$route.query.id || this.$route.params.id
        var data = await this.api.alarmSendConfig({
          url: '/alarmmanage/alarm/send/config/' + id
        })
        if (data.data && data.data.length > 0) {
          this.channel = data.data[0].sendTo
          this.timeSet = data.data[0].sendInterval
          this.theme = data.data[0].alarmTitle
          this.content = data.data[0].alarmContent
          this.count = data.data[0].sendCount
        } else {
          this.theme = this.strategyName
        }
      }
    },
    components: {
      'el-table': Table,
      'el-table-column': TableColumn,
      'el-row': Row,
      'el-col': Col,
      'el-button': Button,
      'el-input': Input,
      'el-select': Select,
      'el-option': Option,
      'el-popover': Popover,
      'el-radio-group': RadioGroup,
      'el-radio': Radio,
      'el-dialog': Dialog
    }
  }
</script>
<style lang="scss" scoped>
  .create-title {
    border-bottom: 1px solid #e5e5e5;
    padding-bottom: 10px;
    font-size: 16px;
    margin-bottom: 30px;
    font-weight: normal;
  }
  .create-input {
    margin-bottom: 15px;
  }
  .create-rule {
    padding: 20px 0;
    border:1px solid #ddd;
    text-align: center;
    border-radius: 5px;
    cursor: pointer;
    user-select: none;
  }
  .create-rule-card {
    margin-bottom: 25px;
    position: relative;
    padding: 25px 0 50px;
    border-radius: 5px;
    border:1px solid #ddd;
    text-align: center;
    user-select: none;
  }
  .create-btn-container {
    margin-top: 25px;
    .create-btn {
      text-align: center;
    }
  }
  .interval {
    margin: 0 6px;
  }
  .rule {
    padding: 0 15px;
  }
  .rule-pad {
    padding-top: 20px;
  }
  .rule-more {
    color: #2b8dd1;
    cursor: pointer;
  }
  .rule-time {
    padding-bottom: 10px;
  }
  .threshold-input {
    width: 100px;
  }
  .rule-more-table {
    text-align: left;
  }
  .rule-close {
    cursor: pointer;
    font-size: 20px;
    position: absolute;
    right: 12px;
    top: 5px;
  }
  .rule-active {
    cursor: pointer;
    color: #2b8dd1;
  }
  .rule-select {
    width: 160px;
  }
  .rule-del-btn {
    cursor: pointer;
    color: #ff4949;
  }
  .rule-bottom-more {
    position: absolute;
    bottom: 0;
    width: 100%;
    height: 30px;
    line-height: 30px;
    border-top: 1px solid #ddd;
    cursor: pointer;
  }
  .hovering:hover {
    background: #f9fafc;
    .el-icon-caret-bottom, .el-icon-caret-top {
      color: #20a0ff;
    }
  }
  .el-icon-caret-bottom, .el-icon-caret-top {
    color: #ddd;
  }
  .rule-threshold-input {
    width: 100px;
  }
  .edit-space {
    height: 40px;
  }
  .set-alarm-label {
    display: inline-block;
    width: 70px;
  }
  .set-alarm-content {
    display: inline-block;
    width: 70%;
  }
  .time-input {
    width: 45px;
  }
  .alarm-set-col {
    margin-bottom: 15px;
  }
  .set-alarm-textarea {
    position: relative;
    top: -70px;
  }
  
</style>

